/**
 * Created by tang on 2018/12/10.
 */
//react
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
//connect
import { connect } from 'dva';
//路由
import { routerRedux, Link } from 'dva/router';
//组件
import { Card, Form, Button, Input, Select, InputNumber, message } from 'antd';
//面包屑和title
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
//queryString
import queryString from 'query-string';
//样式
import styles from './ClassifyAdd.less';
//富文本
import  Editor  from '../../components/Ueditor/Ueditor';
import Cookies from 'universal-cookie';
//const
const FormItem = Form.Item;
const Option = Select.Option;
const { TextArea } = Input;
const cookie = new Cookies();


//表单布局
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 7 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 12 },
    md: { span: 10 },
  },
};

//确定按钮布局
const submitFormLayout = {
  wrapperCol: {
    xs: { span: 24, offset: 0 },
    sm: { span: 10, offset: 7 },
  },
};

//常量
//添加路由
const addPath = '/classify/classifyAdd';
//详情路由
const infoPath = '/classify/classifyInfo';
//清楚model数据 方法
const clear = 'classify/clear';
//存数据
const save = 'classify/save';
//企业实验室项目-列表
const list = 'classify/fetch';
//删除
const del = 'classify/del';
//置顶
const sortType = 'classify/sort';
//审核
const state = 'classify/state';
//更新进度
const progress = 'classify/progress';
//修改时获取信息
const get = 'classify/get';
//添加
const add = 'classify/add';
//修改
const update= 'classify/update';

//权限
//添加权限
const checksAdd = '/admin/item/add';


@connect(
  ({ classify }) => ({ classify })
)
@Form.create()

export default class ClassifyAdd extends Component{

  constructor(props){
    super(props);
    this.state={
      options:[]
    }
  }

  componentDidMount(){
    this.clear();
    this.getQueryString();
  }
  clear(){
    this.props.dispatch({
      type: clear
    })
  }
  //queryString
  getQueryString(){

    var search = queryString.parse(this.props.location.search);
    let type = parseInt(search.type, 10);
    let pid = parseInt(search.pid, 10);
    this.setState({
      type:type,
      pid:pid
    });
    if (search.id){
      let id = parseInt(search.id, 10);
      this.getInfo(id);
    }
  }
  //修改时获得数据
  getInfo(id){
    const { dispatch } = this.props;
    dispatch({
      type: get,
      payload: {
        id: id
      }
    });
    dispatch({
      type:save,
      payload:{
        id:id
      }
    })
  }
  //输入框Input值变化
  inputChange(e){
    let key = e.target.name;
    let value = e.target.value;
    let t = {};
    t[key] = value;
    const { dispatch } = this.props;
    dispatch({
      type: save,
      payload: t
    })
  }

  //InputNumber值变化
  inputNumberChange(name, e){

  }

  handleChange(name,e){
    let t = {};
    t[name] = e;
    this.props.dispatch({
      type:save,
      payload:t
    })
  }

  //添加提交
  sureAct(){
    //检测必填输入框
    const {dispatch, classify: {id, name,classify}} = this.props;
    const {pid} = this.state;
    let data = { name,pid,classify };
    let type = add;
    this.props.form.validateFields((err, fieldsValue) => {
      if (err) {
        return;
      }
      if (id){
        type = update;
        data.id = id;
      }
      dispatch({
        type: type,
        payload: data,
        listType:this.state.type
      })
    });
  }


  render(){
    const { getFieldDecorator } = this.props.form;
    const {classify: {id, name,classify, loading}} = this.props;

    //添加页
    let formItemArray = [];
    let dataArray = [
      {
        name: 'name',
        value: name,
        label: '分类名',
        type: 'Input',
        placeholder: '请输入标题',
        max: 40
      },
      {
        name: 'classify',
        value: classify,
        label: '类型',
        type: 'Select',
        options: [
          <Option value={1} key="type1">自媒体文章</Option>,
          <Option value={2} key="type2">视频</Option>
        ]
      },
    ];
    for (let i = 0; i < dataArray.length; i++){
      let item = dataArray[i];
      let type = item.type;
      switch (type){
        case 'Input':
          formItemArray.push(
            <FormItem
              key={"item-" + i}
              {...formItemLayout}
              label={item.label}
            >
              {getFieldDecorator(item.name, {
                rules: [
                  {required: true, message: item.placeholder}
                ],
                initialValue: item.value
              })(
                <Input maxLength={item.max} name={item.name}  onChange={this.inputChange.bind(this)} placeholder={item.placeholder} />
              )}
            </FormItem>
          );
          break;
        case 'Select':
          formItemArray.push(
            <FormItem
              key={"courtPhone-item-" + i}
              {...formItemLayout}
              label={item.label}
            >
              <Select
                disabled={this.state.type==2||id ? true : false}
                optionFilterProp='children'
                value={item.value?item.value:1}
                //onSearch={this.onSearchChange.bind(this)}
                onChange={this.handleChange.bind(this,item.name)}
              >
                {item.options}
              </Select>
            </FormItem>
          );
          break;
        case 'InputNumber':
          formItemArray.push(
            <FormItem
              key={"item-" + i}
              {...formItemLayout}
              label={item.label}
            >
              <InputNumber disabled={id ? true : false} value={item.value} className={styles.number}  min={0} max={item.max} onChange={this.inputNumberChange.bind(this, item.name)} />
            </FormItem>
          );
          break;
        case 'TextArea':
          formItemArray.push(
            <FormItem
              key={"item-" + i}
              {...formItemLayout}
              label={item.label}
            >
              {getFieldDecorator(item.name, {
                rules: [
                  {required: item.name === 'remark' ? false : true, message: item.placeholder}
                ],
                initialValue: item.value
              })(
                <TextArea className={styles.textArea} autosize={{minRows: 4, maxRows: 4}} maxLength={item.max} name={item.name}  onChange={this.inputChange.bind(this)} placeholder={item.placeholder} />
              )}
            </FormItem>
          );
          break;
        case 'editor':
          formItemArray.push(
            <div key={"item-" + i} title="内容" className={styles.reactQuill}>
              <Editor type="classify" dispatch={this.props.dispatch} updateEditorContent={item.value} id="content" height='200' />
            </div>
          );
          break;
        default: break;
      }
    }

    return(
      <PageHeaderWrapper title={id ? '分类修改' : '分类添加'}>
        <Card bordered={false}>
          <Form
            hideRequiredMark
            style={{ marginTop: 8 }}
          >
            {formItemArray}
            <FormItem {...submitFormLayout} style={{ marginTop: 32 }}>
              <Button type="primary" onClick={this.sureAct.bind(this)} loading={loading}>
                提交
              </Button>
            </FormItem>
          </Form>
        </Card>
      </PageHeaderWrapper>
    )
  }
}
